
package com.sec.android.app.myfiles.fragment.search;

import android.content.Context;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.util.AttributeSet;

import com.sec.android.app.myfiles.R;

import java.util.Locale;

public class SearchTextView extends android.support.v7.widget.AppCompatTextView {

    public SearchTextView(Context context) {
        super(context);
    }

    public SearchTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public SearchTextView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    public void setText(String result, String queries) {
        if (!TextUtils.isEmpty(result) && !TextUtils.isEmpty(queries)) {
            SpannableString span = new SpannableString(result);
            int matchedColor = getResources().getColor(R.color.list_item_matched_text, null);
            String[] queryArray = queries.split("\\s+");
            for (String query : queryArray) {
                int start = 0;
                int index = result.toLowerCase(Locale.getDefault()).indexOf(query.toLowerCase());
                while (index >= 0) {
                    //char[] spanChar = TextUtils.semGetPrefixCharForSpan(getPaint(), result.substring(start), query.toCharArray());
                    char[] spanChar = null;
                    //TODO HYL
                    if (spanChar != null) {

                        String Query = new String(spanChar);
                        index = result.toLowerCase(Locale.getDefault()).indexOf(Query, start);
                        if (index >= 0 && index + query.length() <= result.length()) {
                            span.setSpan(new ForegroundColorSpan(matchedColor), index, index + Query.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                        }
                        start = index + Query.length();
                        index = result.toLowerCase(Locale.getDefault()).indexOf(query, start);
                    } else {
                        if (index >= 0 && index + query.length() <= result.length()) {
                            span.setSpan(new ForegroundColorSpan(matchedColor), index, index + query.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                        }
                        index = result.toLowerCase(Locale.getDefault()).indexOf(query, index + 1);
                    }


                }
            }
            super.setText(span);
        }
    }
}
